package cn.dkdoo.blackhorse_transactional.config;

import cn.dkdoo.utils.config.DkdTransactionConfig;
import cn.dkdoo.utils.config.rollbackData.SaveRollbackDataAbstract;
import cn.dkdoo.utils.config.transactionInfo.TransactionInfoAbstract;
import cn.dkdoo.utils.zookeeper.client.ICuratorCrudRepository;
import cn.dkdoo.utils.zookeeper.client.TypeToken;
import cn.dkdoo.utils.zookeeper.client.impl.CuratorCrudRepositoryImpl;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.lang.reflect.Type;

/**
 * Created by Nicky.Tang on 2021/5/16 3:05 下午
 *
 * @since 02.12.10
 */
@Configuration
public class DkdTransactionConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(DkdTransactionConfiguration.class);

    @Bean
    public ICuratorCrudRepository getZKRepository() throws Exception {
        final ICuratorCrudRepository zkRepository = new CuratorCrudRepositoryImpl();
        return zkRepository;
    }

    @Bean
    public SaveRollbackDataAbstract initSaveRollbackDataAbstract(ICuratorCrudRepository zkRepository) throws Exception {
        return new SaveRollbackDataAbstract() {
            public String getTraNoPath(String traNo) {
                return SaveRollbackDataAbstract.pathPre + traNo;
            }

            @Override
            public void doSave(String traNo, TransactionInfoAbstract info) {
                logger.debug("保存回滚数据：{}\n{}", getTraNoPath(traNo), JSONObject.toJSONString(info));
                zkRepository.setJson(getTraNoPath(traNo), info);
            }

            @Override
            public TransactionInfoAbstract doGet(String traNo) {
                final Type bindType = new TypeToken<TransactionInfoAbstract>() {
                }.getType();
                TransactionInfoAbstract res = null;
                try {
                    res = (TransactionInfoAbstract) zkRepository.getBean(getTraNoPath(traNo), bindType);
                    logger.debug("获取回滚数据：{}\n{}", getTraNoPath(traNo), JSONObject.toJSONString(res));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return res;
            }
        };
    }

    @Bean(name = "dkdTransactionConfig")
    @Primary
    public DkdTransactionConfig initDkdTransactionConfig(SaveRollbackDataAbstract saveRollbackDataAbstract) throws Exception {
        return new DkdTransactionConfig(saveRollbackDataAbstract);
    }

}
